<template>
  <div>
    <el-row style="margin-top: 30px">
      <el-col :span="14"
              :offset="5">
        <header class="headerAdd">选择食品种类</header>

        <el-form label-width="100px"
                 class="form"
                 :model="categoryData"
                 ref="categoryData">
          <el-row class="addFood">
            <el-form-item label="食品种类">
              <el-select v-model="categoryData.selectList"
                         placeholder="请选择"
                         style="width: 100%">
                <el-option v-for="category in categoryData.categoryList"
                           :key="category.id"
                           :label="category.name"
                           :value="`${category.id}:${category.name}`"></el-option>
              </el-select>
            </el-form-item>
          </el-row>
          <el-row class="addFoods"
                  :class="addShow ? 'showHeight' : ''">
            <el-form-item label="食品种类"
                          style="margin-top: 10px"
                          prop="name">
              <el-input v-model="categoryData.name"></el-input>
            </el-form-item>
            <el-form-item label="种类描述"
                          prop="description">
              <el-input v-model="categoryData.description"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary"
                         @click="submitFood(categoryData)">提交</el-button>
            </el-form-item>
          </el-row>
          <div @click="showAddFood"
               class="addType">
            <i class="el-icon-caret-top cicon"
               v-if="addShow"></i>
            <i class="el-icon-caret-bottom cicon"
               v-else></i>
            <span>添加食品种类</span>
          </div>
        </el-form>

        <header class="headerAdd">添加食品</header>
        <el-form label-width="100px"
                 class="form food_form"
                 :model="foodData"
                 :rules="rules"
                 ref="foodData">
          <el-form-item label="食品名称"
                        prop="name">
            <el-input v-model="foodData.name"></el-input>
          </el-form-item>
          <el-form-item label="食品活动"
                        prop="activity">
            <el-input v-model="foodData.activity"></el-input>
          </el-form-item>
          <el-form-item label="食品详情">
            <el-input v-model="foodData.description"></el-input>
          </el-form-item>
          <!-- :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove" -->
          <el-form-item label="食品图片"
                        prop="imgPath">
            <el-upload action="/dev-api/v1/addimg/food"
                       list-type="picture-card"
                       :show-file-list="false"
                       :on-success="handleAvatarSuccess"
                       :before-upload="beforeImgUpload">
              <img width="100%"
                   v-if="foodData.image_path"
                   :src="foodData.image_path" />
              <i v-else
                 class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>

          <el-form-item label="食品特点">
            <el-select v-model="foodData.attributes"
                       multiple
                       placeholder="请选择">
              <!-- v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value" -->
              <el-option v-for="item in attributes"
                         :key="item.value"
                         :value="item.value"
                         :label="item.label">
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 单选框 -->
          <el-form-item label="食品规格">
            <el-radio v-model="foodShow"
                      label="one">单规格</el-radio>
            <el-radio v-model="foodShow"
                      label="more">多规格</el-radio>
          </el-form-item>
          <el-row v-if="foodShow === 'one'">
            <el-form-item label="包装费">
              <el-input-number :min="0"
                               :max="99"
                               v-model="foodData.specs[0].package"></el-input-number>
            </el-form-item>
            <el-form-item label="价格">
              <el-input-number :min="1"
                               :max="99"
                               v-model="foodData.specs[0].price"></el-input-number>
            </el-form-item>
          </el-row>
          <el-row v-else
                  style="text-align: center">
            <el-button type="primary"
                       @click="dialogFood = true">添加规格</el-button>
            <el-table style="width: 100%"
                      :data="foodData.specs">
              <el-table-column prop="specs"
                               label="规格"
                               width="width">
              </el-table-column>
              <el-table-column prop="packing_fee"
                               label="包装费"
                               width="width">
              </el-table-column>
              <el-table-column prop="price"
                               label="价格"
                               width="width">
              </el-table-column>
              <el-table-column prop="prop"
                               label="操作"
                               width="width">
                <template slot-scope="{ row, $index }">
                  <el-button type="danger"
                             size="mini"
                             @click="deleteRank(row, $index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-row>
          <el-form-item>
            <el-button type="primary"
                       @click="addFood">确认添加商品</el-button>
          </el-form-item>
        </el-form>

        <el-dialog title="添加规格"
                   :visible.sync="dialogFood"
                   :show-close="flag">
          <el-form :model="specsForm"
                   :rules="foodPriceRule">
            <el-form-item label="规格"
                          label-width="100px"
                          prop="specs">
              <el-input v-model="specsForm.specs"
                        auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="包装费"
                          label-width="100px">
              <el-input-number v-model="specsForm.packing_fee"
                               :min="0"
                               :max="100"></el-input-number>
            </el-form-item>
            <el-form-item label="价格"
                          label-width="100px">
              <el-input-number v-model="specsForm.price"
                               :min="1"
                               :max="10000"></el-input-number>
            </el-form-item>
          </el-form>
          <div slot="footer"
               class="dialog-footer">
            <el-button @click="dialogFood = false">取 消</el-button>
            <el-button type="primary"
                       @click="addRank">确 定</el-button>
          </div>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  name: "addFood",
  data () {
    return {
      flag: false,
      addShow: false,
      radio: "1",
      foodShow: "one",
      restaurant_id: 1,
      categoryData: {
        //食品种类
        categoryList: [],
        selectList: [],
        name: "",
        description: "",
      },
      foodData: {
        //添加食品数据
        name: "",
        description: "",
        activity: "",
        image_path: "",
        attributes: [],
        specs: [
          {
            specs: "默认",
            packing_fee: 0,
            price: 20,
          },
        ],
      },
      specsForm: {
        specs: "",
        packing_fee: 0,
        price: 20,
      },
      dialogFood: false,
      attributes: [
        {
          value: "新",
          label: "新品",
        },
        {
          value: "招牌",
          label: "招牌",
        },
      ],
      rules: {
        name: [{ required: true, message: "请输入食品名称", trigger: "blur" }],
      },
      foodPriceRule: {
        specs: [{ required: true, message: "请输入规格名称", trigger: "blur" }],
      },
    };
  },
  beforeMount () {
    if (this.$route.query.id) {
      this.restaurant_id = this.$route.query.id;
    } else {
      this.$msgbox({
        title: "提示",
        message: "添加食品需要选择一个商铺，先去就去选择商铺吗？",

        showCancelButton: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        beforeClose: (action, instance, done) => {
          if (action === "confirm") {
            this.$router.push("/datamanage/shopList");

            done();
          } else {
            this.$message({
              type: "success",
              message: "取消",
            });
            done();
          }
        },
      }).then((action) => { });
    }
  },
  mounted () {
    this.getFoodType();
  },
  computed: {
    // selectValue() {
    //   return this.categoryData.categoryList[this.categoryData.selectList] || {};
    // },
  },
  methods: {
    showAddFood () {
      this.addShow = !this.addShow;
    },
    //请求食品种类数据
    async getFoodType () {
      const result = await this.$API.addfoods.getFoodType(this.restaurant_id);
      if (result.status === 1) {
        // console.log(result);
        this.categoryData.categoryList = result.category_list;
      }
    },
    // 提交食品种类
    async submitFood (categoryData) {
      // const categoryData = this.$refs[categoryData];
      // console.log(this.categoryData.selectList)
      if (categoryData.name && categoryData.description) {
        const data = {
          name: this.categoryData.name,
          description: this.categoryData.description,
          restaurant_id: this.restaurant_id,
        };
        try {
          const result = await this.$API.addfoods.addFoodType(data);
          // console.log(result)
          if (result.status == 1) {
            this.getFoodType();
            this.addShow = false;
            this.$message.success("添加食品种类成功");
          }
          // console.log(1111);
        } catch (error) {
          this.$message.warning("添加食品种类失败");
        }
      }
    },
    // 上传图片
    handleAvatarSuccess (res, file) {
      // console.log(res)
      if (res.status == 1) {
        this.foodData.image_path = "https://elm.cangdu.org/img/" + res.image_path;
        // console.log(this.foodData.imgPath);
      } else {
        this.$message.error("上传图片错误");
      }
    },
    // 图片判断合法
    beforeImgUpload (file) {
      const isRightType =
        file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isRightType) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isRightType && isLt2M;
    },
    // 添加规格删除事件
    deleteRank (row, index) {
      this.foodData.specs.splice(index, 1);
    },
    //  添加规格
    addRank () {
      this.foodData.specs.push({ ...this.specsForm });
      (this.specsForm.specs = ""), (this.specsForm.packing_fee = 0);
      this.specsForm.price = 20;
      this.dialogFood = false;
    },
    // 添加食品
    async addFood () {
      let [categoryId, categoryValue] = this.categoryData.selectList.split(":");
      // console.log(categoryId);
      const params = {
        ...this.foodData,
        category_id: categoryId,
        restaurant_id: this.restaurant_id,
      };
      // if (category_id&&restaurant_id) {
      // console.log(params);
      //  console.log(params.img_path)
      try {
        // console.log(params.image_path);
        const result = await this.$API.addfoods.addFood(params);
        console.log(result);
        if (result.status === 1) {
          // console.log(result);
          this.$message({
            type: "success",
            message: "添加成功",
          });
          this.foodData = {
            //添加食品数据
            name: "",
            description: "",
            activity: "",
            image_path: "",
            attributes: [],
            specs: [
              {
                specs: "默认",
                packing_fee: 0,
                price: 20,
              },
            ],
          };
        } else {
          this.$message({
            type: "error",
            message: result.message,
          });
        }
      } catch (err) {
        console.log(err);
      }
    },
  },

  // },
};
</script>

<style  lang="less">
.headerAdd {
  /* width: 1220px; */
  text-align: center;
  margin-bottom: 10px;
}
.form {
  min-width: 400px;
  margin-bottom: 30px;
  &:hover {
    box-shadow: 0 0 8px 0 rgba(232, 237, 250, 0.6),
      0 2px 4px 0 rgba(232, 237, 250, 0.5);
    border-radius: 6px;
    transition: all 400ms;
  }
}
.food_form {
  border: 1px solid #eaeefb;
  padding: 10px 10px 0;
}
.addFood {
  //   width: 90%;
  border: 1px solid #eaeefb;
  align-content: center;
  padding: 10px 30px 10px 10px;
  border-top-right-radius: 6px;
  border-top-left-radius: 6px;
}
.addFoods {
  height: 0;
  overflow: hidden;
  transition: all 400ms;
  background: #f9fafc;
}
.showHeight {
  height: 190px;
}
.addType {
  text-align: center;
  border: 1px solid #eaeefb;
  line-height: 40px;
  border-bottom-right-radius: 6px;
  border-top: none;
  transition: all 400ms;
  span {
    font-size: 14px;
    color: #999;
    transition: all 400ms;
  }
  .cicon {
    color: #ccc;
  }
  &:hover {
    background-color: #f9fafc;
    span,
    .cicon {
      color: skyblue;
    }
  }
  /* &.hover{
     background: blue;
  } */
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
}
</style>